using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace Greg.XmlEditor.Business.Concrete
{
	public class XmlTransformer
	{
		/// <summary>
		/// Transforms an xmlDocument provided into the <paramref name="xmlString"/>
		/// argument using an XSLT file which path is contained into the 
		/// <paramref name="xslPath"/> argument
		/// </summary>
		/// <param name="xmlString">The XML document</param>
		/// <param name="xslPath">The XSLT file path</param>
		/// <returns>The XML document transformed with the XSLT file</returns>
		public static string Transform(string xmlString, string xslPath)
		{
			//load the XML document from xmlString
			var doc = new XPathDocument(new StringReader(xmlString));

			// load the XSLT document from path
			var xslt = new XslCompiledTransform();
			xslt.Load(xslPath);

			// create the output stream
			var stringBuilder = new StringBuilder();
			var stringWriter = new StringWriter(stringBuilder);
			var xmlWriter = new XmlTextWriter(new StringWriter(stringBuilder));

			// execute XSL transformation
			xslt.Transform(doc, xmlWriter);

			// close all temporary streams
			xmlWriter.Flush();
			xmlWriter.Close();
			stringWriter.Flush();
			stringWriter.Close();

			// return the XSL transformed document
			return stringBuilder.ToString();
		}
	}
}